package gui.utilities;

import gui.panels.LogsArea;

import java.util.logging.Filter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

import javax.swing.SwingUtilities;

public class LogsHandler extends Handler {
	
	@Override
	public synchronized void setLevel(Level newLevel) throws SecurityException {
		this.level = newLevel;
		super.setLevel(newLevel);
	}

	private static LogsArea logsArea;
	
	public static void setLogsArea(LogsArea logsArea) {
		LogsHandler.logsArea = logsArea;
	}
	
	private Level level = Level.INFO;
	
	public LogsHandler() {
		Filter filter = new Filter() {
			@Override
			public boolean isLoggable(LogRecord arg0) {
				return arg0.getLevel().intValue() >= level.intValue();
			}
		};
		this.setFilter(filter);
	}
	
	@Override
	public void close() throws SecurityException { }

	@Override
	public void flush() { }

	@Override
	public void publish(LogRecord record) {
		if (!getFilter().isLoggable(record))
			return;
		final String message = new LogsFormatter().format(record);
		logsArea.append(message);
//		SwingUtilities.invokeLater(new Runnable() {
//			@Override
//			public void run() {
//				logsArea.append(message);
//			}
//		});
	}

}
